/* BusMaterialAccountBusiness.java
 *
 * Project/Product: GW
 *
 * Modify Information:
 * =============================================================================
 *   Author	Date       Description
 *   ----------	---------- ---------------------------------------------------
 *   Administrator	2008-5-19	First release
 *
 * Licensed Materials - Property of APEP
 * =============================================================================
 *    (C) COPYRIGHT Shanghai Auto Mart E-Procurement Co., Ltd. 2007 - 2008
 *    All Rights Reserved.
 *
 *    This software is the confidential and proprietary information of
 *    Shanghai Auto Mart E-Procurement Co., Ltd. ("Confidential Information").
 *    You shall not disclose such Confidential Information and shall use it only
 *    in accordance with the terms of the license agreement you entered into 
 *    with Shanghai Auto Mart E-Procurement Co., Ltd.
 *
 * Noties:
 * =============================================================================
 * 
 */

package system.base;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import system.data.BusMaterialAccountKilPageData;
import system.data.BusMaterialAccountPageData;

import framework.core.DBConnection;
import framework.core.DBEngine;
import framework.core.DBResult;
import framework.core.DateUtil;
import framework.core.StringUtil;

/** 车辆维修材料费用分析各种业务方法    
 *  提供给:
 *  BusMaterialAccount
 *  BusMaterialAccountKil
 *  使用*/
public class BusMaterialAccountBusiness {
    public static final String[] months = {"01","02","03","04","05","06","07","08","09","10","11","12"};
    
    /** 时间组合 根据一个YYYMM 返回一个YYYY-MM-DD HH:MM:SS时间格式的数组 包含两个元素 最小时间 最大时间 */
    private static String[] makeTime(String year, String month) throws Exception {
        String min = "-01 00:00:00";
        String max = " 23:59:59";
        int days = DateUtil.getMaxDayOfMonth(Integer.parseInt(year), Integer.parseInt(month));
        min = year + "-" + month + "min";
        max = year + "-" + month + "-" + String.valueOf(days) + max;
        String[] day = new String[] { min, max };
        return day;
    }

    /** 判断是否在执行大于等于本年月的数据整理 */
    private static boolean checkBalanceTime(String[] values) {
        boolean result = false;
        Date date = new Date();
        int year = date.getYear();
        int month = date.getMonth() + 1;
        int s_year = Integer.parseInt(values[1]);
        if (s_year < year) {
            result = true;
        } else {
            int s_month = Integer.parseInt(values[2]);
            if (month < s_month) {
                result = true;
            } else {
                result = false;
            }
        }
        return result;
    }

    /** 获得单一金额结果 通用方法 */
    private static String getResult(String sql, DBConnection con) throws Exception {
        DBResult dbs = DBEngine.doSelect(con, sql);
        ResultSet rs = dbs.getRs();
        String money = "";
        if (rs.next()) {
            double result = rs.getDouble(1);
            money = String.valueOf(result);
        } else {
            money = "0.0";
        }
        rs.close();
        dbs.clear();
        return money;
    }

    /** 使一个集合的值转换为数组 */
    private static String[] setStrArray(Vector vec) {
        int size = vec.size();
        String[] str = new String[size];
        for (int i = 0; i < size; i++) {
            str[i] = (String) vec.get(i);
        }
        return str;
    }

    /** 去除一个数组重复项 返回一个新的数组  元素唯一*/
    public static String[] setStrArray(String[] str) {
        List list = Arrays.asList(str);
        Set set = new HashSet(list);
        String[] temp = new String[set.size()];
        Iterator ite = set.iterator();
        for (int i = 0; ite.hasNext(); i++) {
            temp[i] = (String) ite.next();
        }
        return temp;
    }
    
    /** 得到全记录   BusMaterialAccount BusMaterialAccountKil 通过SQL中的表名来判断*/
    public static Vector getFullData(String sql,DBConnection con) throws Exception{
        Vector vec = new Vector();
        DBResult dbs = DBEngine.doSelect(con, sql);
        ResultSet rs = dbs.getRs();
        while (rs.next()) {
            String[] values = new String[7];
            values[0] = rs.getString(1);
            values[1] = rs.getString(2);
            values[2] = rs.getString(3);
            values[3] = rs.getString(4);
            values[4] = rs.getString(5);
            values[5] = rs.getString(6);
            values[6] = String.valueOf(rs.getDouble(7));
            vec.add(values);
        }
        rs.close();
        dbs.clear();
        return vec;
    }
    
    /** 从集合中取出数组对象  并且将指定的索引位置的值取出  组成一个新的数组*/
    public static String[] getStr(Vector vec,int index){
        String[] values = new String[vec.size()];
        for (int i = 0; i < vec.size(); i++) {
            String[] str = (String[])vec.get(i);
            values[i] = str[index];
        }
        return values;
    }
    
    
    /** 获得查询结果的行数*/
    public static int getNumRows(ResultSet rs) throws Exception{
        //通过改方法获取结果集的行数
        int result = 0;
        if (rs.last()){
            result = rs.getRow();
            rs.beforeFirst();//光标回滚
        }
        return result;
    }

    
    /** 判断一个字符串是否存在于另一个字符串中 不考虑大小写*/
    private static boolean checkStr(String father,String son){
        father = father.toUpperCase();
        son = son.toUpperCase();
        int i = father.indexOf(son);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }
    
    
    
    public static String[] getValuesByIndexValueEquals(Vector vec,String str,int index1,int index2){
        Vector temp = new Vector();
        for (int i = 0; i < vec.size(); i++) {
            String[] obj = (String[])vec.get(i);
            if(obj[index1].equals(str)){
                temp.add(obj[index2]);
            }
        }
        String[] needed = setStrArray(temp);
        needed = setStrArray(needed);
        return needed;
    }
    
    public static String[] getValuesByIndexValueEquals(Vector vec,String str1,String str2,int index1,int index2,int index3){
        Vector temp = new Vector();
        for (int i = 0; i < vec.size(); i++) {
            String[] obj = (String[])vec.get(i);
            if(obj[index1].equals(str1) && obj[index2].equals(str2)){
                temp.add(obj[index3]);
            }
        }
        String[] needed = setStrArray(temp);
        needed = setStrArray(needed);
        return needed;
    }
        
    /** 根据车号000000    年0000   月00   得到界面一系列所需金额*/
    public static String[] getMoneyValues(String year,String month,String busTag,String warehouseCode,DBConnection con)throws Exception{
        String str = "select sum(REPAIRED_MONEY) from T_BUS_MATERIAL_ACCOUNT where WAREHOUSE_CODE = ";
        String str1 = "select avg(REPAIRED_MONEY) from T_BUS_MATERIAL_ACCOUNT where WAREHOUSE_CODE = ";
        int nowYear = Integer.parseInt(year);
        int nowMonth = Integer.parseInt(month);
        int lastYear = nowYear - 1;
        int lastMonth = nowMonth - 1;
        String lastYearStr = "" + lastYear;
        String lastMonthStr = "";
        if(lastMonth == 0){
            lastMonth = 12;
        }
        if(lastMonth < 10){
            lastMonthStr = "0" + lastMonth;
        }else{
            lastMonthStr = "" + lastMonth;
        }
        String[] moneys = new String[10];
        String[] sql = new String[6];
        
        //上月费用
        sql[0] = "";
        if(lastMonth == 12){
            sql[0] = str+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+lastYearStr+lastMonthStr+"%'";
        }else{
            sql[0] = str+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+year+lastMonthStr+"%'";
        }
        //本月费用
        sql[1] = str+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+year+month+"%'";
        //当年累计费用
        sql[2] = str+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+year+"%'";
        //当年月平均费用
        sql[3] = str1+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+year+"%'";
        //去年月平均费用
        sql[4] = str1+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+lastYearStr+"%'";
        //本月同比  得到去年本月的数据
        sql[5] = str+"'"+warehouseCode+"' and BUS_TAG = '"+busTag+"' and REPAIREN_TIME like '"+lastYearStr+month+"%'";
        //本月环比  调用sql0后 再做处理
        
        for (int i = 0; i < sql.length; i++) {
            moneys[i] = getResult(sql[i], con);
            if(moneys[i] == null || moneys[i].equals("")){
                moneys[i] = "0.0";
            }
        }
        /**
         * money元素:
         * 0.上月费用
         * 1.本月费用
         * 2.当年累计费用
         * 3.当年月平均费用
         * 4.去年月平均费用
         * 5.去年本月的数据
         * 6.本月同比绝对值
         * 7.本月同比百分率
         * 8.本月环比绝对值
         * 9.本月环比百分率
         * */
        moneys[6] = String.valueOf(Math.abs(Double.parseDouble(moneys[1]) - Double.parseDouble(moneys[5])));  
        if(Double.parseDouble(moneys[5]) > 0){
            double temp = Double.parseDouble(moneys[1]) - Double.parseDouble(moneys[5]);
            temp = temp/Double.parseDouble(moneys[5]);
            temp = temp * 100;
            moneys[7] = String.valueOf(temp);
        }else{
            moneys[7] = "0";
        }
        moneys[8] = String.valueOf(Math.abs(Double.parseDouble(moneys[1]) - Double.parseDouble(moneys[0])));  
        if(Double.parseDouble(moneys[0]) > 0){
            double temp = Double.parseDouble(moneys[1]) - Double.parseDouble(moneys[0]);
            temp = temp/Double.parseDouble(moneys[0]);
            temp = temp * 100;
            moneys[9] = String.valueOf(temp);
        }else{
            moneys[9] = "0";
        }
        return moneys;
    }
    /** 分区数组*/
    
    
    /** 算取金额    用于界面的同比环比*/
    public static double[] countMoney(double[] counts){
        counts[6] = Math.abs(counts[1] - counts[5]);  
        if(counts[5] > 0){
            double temp = counts[1] - counts[5];
            temp = temp/counts[5];
            temp = temp * 100;
            counts[7] = temp;
        }else{
            counts[7] = 0.0;
        }
        counts[8] = Math.abs(counts[1] - counts[0]);  
        if(counts[0] > 0){
            double temp = counts[1] - counts[0];
            temp = temp/counts[0];
            temp = temp * 100;
            counts[9] = temp;
        }else{
            counts[9] = 0.0;
        }
        return counts;
    }
    
    /** 根据年0000 得到  需要进行    最高\最低\平均    数据处理的   数据结果*/
    public static Vector getResultByYear(String year,DBConnection con)throws Exception{
        String sql = "select warehouse_code, max(money),min(money),avg(money) from ( select warehouse_code,substr(repairen_time, 1, 6) rt,sum(repaired_money) money from t_bus_material_account where repairen_time like '"+year+"%' group by warehouse_code,substr(repairen_time, 1, 6) order by warehouse_code,substr(repairen_time, 1, 6)) group by warehouse_code";
        Vector vec = new Vector();
        DBResult dbs = DBEngine.doSelect(con, sql);
        ResultSet rs = dbs.getRs();
        while (rs.next()) {
            String[] values = new String[4];
            values[0] = rs.getString(1);
            values[1] = String.valueOf(rs.getDouble(2));
            values[2] = String.valueOf(rs.getDouble(3));
            values[3] = String.valueOf(rs.getDouble(4));
            vec.add(values);
        }
        rs.close();
        dbs.clear();
        return vec;
    }
    
//    private static Map getmax(Map map,String year){
//        double money = 0;
//        for (int i = 0; i < 12; i++) {
//            double current = Double.parseDouble((String)(map.get(year + months[i])));
//            if(money < current){
//                money = current;
//                map.put("max", String.valueOf(money));
//                map.put("maxyear", year);
//                map.put("maxmonth", months[i]);
//            }
//        }
//        return map;
//    }
//    
//    private static Map getmin(Map map,String year){
//        double money = 0;
//        for (int i = 0; i < 12; i++) {
//            double current = Double.parseDouble((String)(map.get(year + months[i])));
//            if(i == 0){
//                money = current;
//            }
//            if(money > current){
//                money = current;
//                map.put("min", String.valueOf(money));
//                map.put("minyear", year);
//                map.put("minmonth", months[i]);
//            }
//        }
//        return map;
//    }
//    
//    private static Map getavg(Map map,String year){
//        double money = 0;
//        for (int i = 0; i < 12; i++) {
//            double current = Double.parseDouble((String)(map.get(year + months[i])));
//            money += current;
//        }
//        money = money/12;
//        map.put("avg", String.valueOf(money));
//        return map;
//    }
//    
//    public static Vector getResult6004(String year,DBConnection con)throws Exception{
//        Vector vec = getResultByYear(year, con);
//        Vector end = new Vector();
//        for (int i = 0; i < vec.size(); i++) {
//            Map map = (Map)vec.get(i);
//            map = getmax(map, year);
//            map = getmin(map, year);
//            map = getavg(map, year);
//            end.add(map);
//        }
//        return end;
//    }
}
